package dsk.demo.product.controller.product;

import cn.hutool.http.HttpUtil;
import dsk.demo.common.utils.R;
import dsk.demo.product.entity.ProductCarEntity;
import dsk.demo.product.entity.ProductRefEntity;
import dsk.demo.product.service.ProductCarService;
import dsk.demo.product.service.ProductRefService;
import dsk.demo.product.util.StrUtil;
import dsk.demo.product.util.UrlUtil;
import lombok.Data;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class DataRefController {

    //cookie值   15天需要手动更新一次
    private static String cookieValue = "language=en-us; user=dsk74520; SupId=2248330; security_session_verify=0a13a6b6d8281a09c2dfd67dd22ed668; ASP.NET_SessionId=lghqws1zpm0uwpxsbevvocyk; pass=90F7AD4CAD19AFD3; IsLogin=true";

    @Autowired
    private ProductCarService productCarService;

    @Autowired
    private ProductRefService productRefService;

    /**
     * type = 3   OEM列表
     * type = 9   大厂编号
     * type = 4   适配车型
     *
     * @param url
     * @return
     */
    @PostMapping("/niparts")
    public Map<String, Object> niparts(@RequestBody String url) throws Exception {
        //分析这个url,获取他的  type是多少
        String baseUrl = url.split("\\?")[0];
        List<ProductRefEntity> oemList = new ArrayList<>();
        List<ProductRefEntity> crossList = new ArrayList<>();
        //获取OEM
        Map<String, String> params = UrlUtil.getParams(url);
        try {
            params.put("type", "3");
            oemList = getOem(baseUrl, params);
        } catch (Exception e) {
            System.out.println(e);
        }


        //获取Cross
        try {
            params.put("type", "9");
            crossList = getCross(baseUrl, params);
        } catch (Exception e) {
            System.out.println(e);
        }
        oemList.addAll(crossList);

        List<ProductCarEntity> carList = new ArrayList<>();
        //获取车型
        try {
            params.put("type", "4");
            carList = getCars(baseUrl, params);
        } catch (Exception e) {
            System.out.println(e);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("oemList", oemList);
        resultMap.put("carList", carList);
        return resultMap;
    }

    @PostMapping("/saveNiparts")
    public R save(@RequestBody NipartsDto data) throws Exception {
        String searchProductNo = StrUtil.getFoundString(data.getProductNo());
        String productNo = data.getProductNo().trim();
        if (data.carList != null && data.carList.size() > 0) {
            data.carList.stream().forEach(car -> {
                car.setProductNo(productNo);
            });
            productCarService.insertBatch(data.carList.stream().collect(Collectors.toSet()));
        }
        if (data.oemList != null && data.oemList.size() > 0) {
            data.oemList.stream().forEach(oem -> {
                oem.setProductNo(productNo);
                oem.setSearchProductNo(searchProductNo);
                oem.setSearchNo(dsk.demo.product.util.StrUtil.getFoundString(oem.getRefNo()));
            });
            productRefService.insertBatch(data.oemList.stream().collect(Collectors.toSet()));
        }
        return R.ok("数据添加成功");
    }


    public List<ProductRefEntity> getOem(String baseUrl, Map params) throws Exception {
        List<ProductRefEntity> resultList = new ArrayList<>();
        String realUrl = UrlUtil.getRealUrl(baseUrl, params);
        String result = HttpUtil.createGet(realUrl).header("Cookie", cookieValue).execute().body();
        Document doc = Jsoup.parse(result);
        Element body = doc.body();
        //1. table id Crl_GridView_OEM
        Element table = body.getElementById("Crl_GridView_OEM");
        if (table == null) {
            throw new Exception("不存在OEM 表单元素,可能是cookie过期了");
        }
        //2. 拿到下面所有的 tr 标签
        Elements trList = table.getElementsByTag("tr");
        //3. 遍历tr标签集合
        for (Element element : trList) {
            Elements tdList = element.getElementsByTag("td");
            if (tdList.size() != 2) {
                continue;
            }
            ProductRefEntity productRefEntity = new ProductRefEntity();
            productRefEntity.setBrand(tdList.get(0).ownText());
            productRefEntity.setRefNo(tdList.get(1).ownText());
            resultList.add(productRefEntity);
        }
        return resultList;
    }

    public List<ProductRefEntity> getCross(String baseUrl, Map params) throws Exception {
        List<ProductRefEntity> resultList = new ArrayList<>();
        String realUrl = UrlUtil.getRealUrl(baseUrl, params);
        String result = HttpUtil.createGet(realUrl).header("Cookie", cookieValue).execute().body();
        Document doc = Jsoup.parse(result);
        Element body = doc.body();
        //1. table id Crl_GridView_OEM
        Element table = body.getElementById("Crl_GridView_Fac");
        if (table == null) {
            throw new Exception("不存在OEM 表单元素,可能是cookie过期了");
        }
        //2. 拿到下面所有的 tr 标签
        Elements trList = table.getElementsByTag("tr");
        //3. 遍历tr标签集合
        for (Element element : trList) {
            Elements tdList = element.getElementsByTag("td");
            if (tdList.size() != 2) {
                continue;
            }
            ProductRefEntity productRefEntity = new ProductRefEntity();
            productRefEntity.setBrand(tdList.get(0).ownText());
            productRefEntity.setRefNo(tdList.get(1).ownText());
            resultList.add(productRefEntity);
        }
        return resultList;
    }

    public List<ProductCarEntity> getCars(String baseUrl, Map params) throws Exception {
        List<ProductCarEntity> carList = new ArrayList<>();
        String realUrl = UrlUtil.getRealUrl(baseUrl, params);
        String result = HttpUtil.createGet(realUrl).header("Cookie", cookieValue).execute().body();
        Document doc = Jsoup.parse(result);
        Element body = doc.body();
        //1. table id Crl_GridView_OEM
        Element cardetaillist = body.getElementById("Crl_GridView_Car");
        if (cardetaillist != null) {
            Elements tr = cardetaillist.getElementsByTag("tr");
            if (!tr.isEmpty()) {
                //车型不为空
                Elements onclicks = cardetaillist.getElementsByAttribute("onclick");
                for (Element model : onclicks) {
                    if (!model.nodeName().equals("tr")) {
                        continue;
                    }
                    //品牌 + 车系  用下划线分割
                    String brand = model.getElementsByTag("font").get(0).ownText();
                    String idStr = model.attr("onclick").split("\\'")[1];
                    //找到隐藏的 车型元素
                    int i = 0;
                    while (true) {
                        Element elementById = cardetaillist.getElementById(idStr + i);
                        if (elementById == null) {
                            break;
                        }
                        //车型全名
                        ProductCarEntity entity = new ProductCarEntity();
                        entity.setBrand(brand);
                        entity.setFullname(brand + " " + elementById.child(0).ownText() + " " + elementById.child(6).child(0).ownText());
                        carList.add(entity);
                        i++;
                    }
                }
            }
        }
        return carList;
    }


    @Data
    public static class NipartsDto {
        private String productNo;
        List<ProductRefEntity> oemList = new ArrayList<>();
        List<ProductCarEntity> carList = new ArrayList<>();
    }
}
